<script lang='ts'>
import { AxiosResponse } from 'axios'
import { ElLoading } from 'element-plus'
import { nextTick } from 'vue'
import { defineComponent, reactive } from 'vue'
import { ReturnTree } from '/@/_types/api/return-type'
export default defineComponent({
    name: "JxtechAsyncTree"
})
</script>
<script lang="ts" setup>

const props = defineProps({
    loadData: {
        type: Function,
        required: true
    },
    // label 树显示的文字 chirdren 子节点
    props: {
        type: Object,
        default: () => {
            return {
                label: 'text',
                children: 'children',
                isLeaf: 'leaf'
            }
        }
    },
    // 内容为空时候显示的文字
    emptyText: {
        type: String,
        default: '数据正在加载中'
    },
    lazy: {
        type: Boolean,
        default: true
    },
})
//共三个参数，依次为：传递给 data 属性的数组中该节点所对应的对象、节点对应的 Node、节点组件本身。
const emit = defineEmits<{
    (e: 'node-click', row: ReturnTree<any>, column: any, event: Event): void//行点击事件
}>()

const JxtechAsyncTreeState = reactive({
    asyncTreeLoading: false,
    /**过滤树数据 */
    filterTreeData: (treeData: ReturnTree<any>[]) => {
        const treeNodeArr: any[] = []
        treeData.forEach(item => {
            let treeNode: any = item
            treeNode.leaf = !item.isParent
            treeNodeArr.push(treeNode)
        })
        return treeNodeArr
    },
    /**异步树加载 */
    loadNode: (node: any, resolve: any) => {
        let loadingInstance: any
        if (node.level == 0) {
            nextTick(() => {
                JxtechAsyncTreeState.asyncTreeLoading = true
            })
        }

        let queryparam: any = {}
        queryparam.id = node.level === 0 ? '0' : node.data.id
        props.loadData(queryparam).then((res: AxiosResponse<ReturnTree<any>[]>) => {
            resolve(JxtechAsyncTreeState.filterTreeData(res.data))
        }).finally(() => {
            JxtechAsyncTreeState.asyncTreeLoading = false
        })
    },
    /**节点点击事件 */
    handleNodeClick: (treeData: ReturnTree<any>, column: any, event: Event) => {
        emit("node-click", treeData, column, event)
    },
})
</script>
<template>
    <el-tree
        v-loading="JxtechAsyncTreeState.asyncTreeLoading"
        highlight-current
        class="jxtech-async-tree"
        :props="props.props"
        :empty-text="emptyText"
        :lazy="lazy"
        :load="JxtechAsyncTreeState.loadNode"
        @node-click="JxtechAsyncTreeState.handleNodeClick"
    >
        <template #default="{ node }">
            <jxtech-svg-icon :icon="'#icon-attachent'" :size="24"></jxtech-svg-icon>
            <span class="jxtech-async-tree-node">
                <span :title="node.label">{{ node.label }}</span>
            </span>
        </template>
    </el-tree>
</template>
<style lang="scss" scoped>
::v-deep(.el-tree) {
    height: 100%;
    overflow: auto;
}
</style>